var ani = ani || {};
ani.util = ani.util || {};
ani.ui = ani.ui || {};
ani.ui.menu = ani.ui.menu || {};
ani.ui.menu.sub = ani.ui.sub || {};
ani.ui.notice = ani.ui.notice || {};

//=======BASE ELEMENT=======
ani.ui.generateHTMLMark = function(markName){
	return $('<' + markName + '></' + markName + '>');
}
ani.ui.generateSingleHTMLMark = function(markName){
	return $('<' + markName + '/>');
}
ani.ui.constructListElem = function(mark, content, id, url){
    //mark - li or ul
	var listMark = ani.ui.generateHTMLMark(mark);
	if(id != null){null,
	    listMark.attr('id', id);
	}
	if(content != null && content != ''){
	    var linkMark = ani.ui.generateHTMLMark('a');
	    linkMark.html(content);
	    linkMark.attr('href', '#');
        listMark.bind('click', function(){
            ani.ui.menu.clickMenu(listMark, url)
            });
	    listMark.append(linkMark);
	}
	return listMark;
}
ani.ui.isSuccess = function(obj){
    if(obj.success == true){
        return true;
    }else{
        return false;
    }
}
/**
 * Call asynchronous REST API
 * @return is success
 * @param apiUrl
 * @param paramsMap
 */
ani.ui.callServer = function(apiUrl, paramsMap, httpMethod){
    var _this = this;
    $.ajaxSettings.async = false;
//    $.getJSON(
//        apiUrl,
//        paramsMap,
//        function(obj){
//            if(ani.ui.isSuccess(obj)){
//                _this.retData = obj.data;
//            }else{
//                ani.ui.notice.alertMessage(obj.message);
//            }
//        }
//    );
    $.ajax(
        {
            data: paramsMap,
            dataType: 'json',
            success: function(obj){
                if(ani.ui.isSuccess(obj)){
                    _this.retData = obj.data;
                }else{
                    _this.retData = obj.data = false;
                    ani.ui.notice.alertMessage(obj.message);
                }
            },
            url: apiUrl,
            type: httpMethod
        }
    );
    return _this.retData;
}
ani.ui.getObjList = function(objUrl, callParams){
	var _this = this;
	$.ajaxSettings.async = false;
	$.getJSON(
		objUrl,
        callParams,
		function(obj){
		    if(obj.success){
			    _this.retData = obj.data;
		    }else{
                ani.ui.notice.alertMessage(obj.message);
		    }
		}
	);
	return _this.retData;
}
ani.ui.displayObj = function(isDisplay, elem){
    var displaySpeed = 176;
    //alert(elem.css('display'));
    if(elem){
        if(isDisplay){
            elem.slideDown(displaySpeed);
        }else if(!isDisplay){
            elem.slideUp(displaySpeed);
            window.setTimeout(
                function(){
                    elem.remove();
                },
                displaySpeed);
        }else{
            elem.remove();
        }
    }
}
ani.ui.loadUserInfo = function(containerId){
    var userEmail = $.cookie('aniUserEmail');
    if(userEmail != undefined){
        $('#' + containerId).html(userEmail);
    }else{
        window.location.href = '/user/login';
    }
}
//=======NOTICE=======
ani.ui.notice.alertMessage = function(msg){
	alert(msg);			//TODO ani-style message box
}
ani.ui.notice.general = function(msg){
	alert(msg);			//TODO ani-style message box
}
ani.ui.notice.pageMessage = function(msg, container){
    alert(msg);         //TODO page message
}
//=======NAV BAR=======
ani.ui.menu.constructNavListElement = function(navList, bannerElem){
	var rootUlElem = ani.ui.constructListElem('ul', null, null, null);
	$.each(
        navList,
        function(objId, oneObj){
            var subMenuObjs = oneObj.subMenuObjs;
            var subListElem = ani.ui.constructListElem('li', oneObj.label, oneObj.tag, oneObj.url);
            subListElem.bind('click', ani.ui.menu.discardSubmenu);
            rootUlElem.append(subListElem);
            if(subMenuObjs != null && subMenuObjs.length != 0){
                subListElem.bind(
                    'click',
                    function(){
                        var subMenuObj = $('#anisubmenu');
                        if(subMenuObj.length < 1){
                            ani.ui.menu.sub.create(ani.ui.menu.constructNavListElement(subMenuObjs), bannerElem);
                        }
                        ani.ui.displayObj(true, $('#anisubmenu'));
                });
            }
        });
	return rootUlElem;
}
ani.ui.menu.loadMenu = function(menuElemUrl){
    $('section').bind('click', ani.ui.menu.discardSubmenu);
    $('footer').bind('click', ani.ui.menu.discardSubmenu);
	var $aninav = $('#aninav');
	var bannerElem = $('#aniheader');
	var navListObj = ani.ui.getObjList(menuElemUrl);
	var navListElement = ani.ui.menu.constructNavListElement(navListObj, bannerElem);
	$aninav.append(navListElement);
}
ani.ui.menu.clickMenu = function(caller, url){
    if(url != null && url != ""){
        ani.ui.triggerMenuElement(url);
//        ani.ui.loadPage('#anicontainer', url);
    }else{
        ani.ui.displayObj(true, caller.find('ul'));
    }
}
ani.ui.menu.sub.create = function(objUlList, bannerElem){
    var subMenuContainer = ani.ui.generateHTMLMark('nav');
    subMenuContainer.attr('id', 'anisubmenu');
    //subMenuContainer.css('display', 'none');
    subMenuContainer.append(objUlList);
    bannerElem.append(subMenuContainer);
}
ani.ui.menu.discardSubmenu = function(){
    var submenuObj = $('#anisubmenu');
    if(submenuObj != null){
        ani.ui.displayObj(false, submenuObj);
    }
}
//=======PAGE=======
ani.ui.constructPageObj = function(onePage, callParamsObj){
	//frame
	var sectionMark = ani.ui.generateHTMLMark('section');
	//page title
	var titleMark = ani.ui.generateHTMLMark('h1');
	titleMark.html(onePage.title);
	sectionMark.append(titleMark);
	ani.ui.changePageTitle(onePage.title);
	//page description
	var descMark = ani.ui.generateHTMLMark('p');
	descMark.html(onePage.description);
	sectionMark.append(descMark);
	//entity
	if(onePage.pageType && onePage.pageType != ""){
        var templateObj = ani.ui.template[onePage.pageType](onePage, callParamsObj);
        sectionMark.append(templateObj);
	}
	return sectionMark;
}
ani.ui.changePageTitle = function(title){
    var suffix = 'Anicloud';
    $('title').html(title + ' - ' + suffix);
}
ani.ui.noticeBox = function(){
	var boxMark = ani.ui.generateHTMLMark('dialog');
	boxMark.attr('id', 'aniNoticeBox');
	return boxMark;
}
ani.ui.loadPage = function(container, pageElemUrl, params, callParams){
    if(pageElemUrl && pageElemUrl.trim() != ""){
        var pageContainer = $(container);
        pageContainer.html("");
        var onePage = ani.ui.getObjList(pageElemUrl, callParams);
        pageContainer.append(ani.ui.constructPageObj(onePage, params));
    }
}
//=======CONTENT=======
ani.ui.triggerMenuElement=function(url, params, callParams){
    ani.ui.loadPage('#anicontainer', url, params, callParams);
}
ani.ui.convertFormToObject = function(formObj){
    var retObj = new Object();
    var formObjValueArr = formObj.serializeArray();
    for(var idx in formObjValueArr){
        retObj[formObjValueArr[idx].name] = formObjValueArr[idx].value || '';
    }
    return retObj;
}
//======BASIC FUNCTIONS======
ani.util.Expression = function(expressionString, argsValueMap){
    var _this = this;
    _this.srcExpression = expressionString;
    var contentParts = [];
    _this.argumentsArr = [];
    _this.getFullResult= function(){
        return _this.srcExpression.replace(
            /{\w*}/g,
            function(key){
                key = key.substring(1, key.length - 1);
                return argsValueMap[key];
            }
        );
    }
}